package cn.comon.app.scan.service.analysis.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import cn.comon.app.scan.entity.AsReportinfo;
import cn.comon.app.scan.service.analysis.IAnalysisProccess;
import cn.comon.app.scan.service.analysis.IAnalysisRequest;
import cn.comon.app.scan.service.analysis.IAnalysisResponse;
import cn.comon.app.scan.util.SpringContextUtil;

/**
 * 向第三方软件检测机构发送数据处理类
 * @author xujf
 *
 */
@Service
public class AnalysisProccessImpl implements IAnalysisProccess {
	
    private Properties params = null;
    private List<AsReportinfo> appDataList = null;
    private String type = null;
    private static Logger logger = Logger.getLogger(AnalysisProccessImpl.class.getName());
    
    public AnalysisProccessImpl(){
    }
    
    public AnalysisProccessImpl(Properties params, List<AsReportinfo> appDataList, String type){
        this.params = params;
        this.appDataList = appDataList;
        this.type = type;
    }
    
    public void run() {
        try {
            this.process(this.params, this.appDataList, this.type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private boolean process(Properties params, List<AsReportinfo> appDataList, String type) {
        for (AsReportinfo asReportinfo:appDataList) {
            // 向发送数据
            logger.debug("开始发送Reportinfo.ID=【" + asReportinfo.getId() + "】...");
            this.doProcess(params, asReportinfo, this.type);
            logger.debug("发送Reportinfo.ID=【" + asReportinfo.getId() + "】完成...");
        }
    	return true;
    }
    /**
     * 获取连接
     * @param url
     * @return
     */
    private HttpURLConnection getHttpURLConnection(String url) {
    	HttpURLConnection connection = null;
    	try {
    		URL request = new URL(url);
    		connection = (HttpURLConnection)request.openConnection();

            //构造post请求
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            //设置连接主机超时（单位：毫秒）。1000 毫秒= 1秒
            connection.setConnectTimeout(30000);
            //设置从主机读取数据超时（单位：毫秒）
            connection.setReadTimeout(30000);
            
            return connection;
    	} catch (Exception e) {
    	    logger.error("AnalysisProccessImpl.getHttpURLConnection:" + e);
    		return null;
    	}
    }
    
    /**
     * 执行
     * @param params
     * @param asReportinfo
     * @param type
     */
    private void doProcess(Properties params, AsReportinfo asReportinfo, String type) {
    	HttpURLConnection connection = null;
    	JSONObject sendData = null;
    	Object resultJson = null;
    	try {
			// 获取接口数据
    		IAnalysisRequest analysisRequest = (IAnalysisRequest)SpringContextUtil.getBean(type + "RequestImpl");
    		sendData = (JSONObject)analysisRequest.getSendData(params, asReportinfo);
    		
    		// 获取连接
    		connection = this.getHttpURLConnection(sendData.getString("sendUrl"));
    		// 发送数据
    		resultJson = this.send(connection, sendData.getString("postData"));
            // 更新发送结果
    		IAnalysisResponse analysisResponse = (IAnalysisResponse)SpringContextUtil.getBean(type + "ResponseImpl");      
            analysisResponse.processResponse(params, asReportinfo, resultJson);
		} catch(Exception e) {
		    logger.error(e);
		}
    }
    

    /**
     * 发送数据
     * @param connection
     * @param postData
     * @return
     */
    private Object send(HttpURLConnection connection, String postData) {
		try {
			//获取需要检测的软件信息。
	        DataOutputStream writeStream = new DataOutputStream(connection.getOutputStream());
	        writeStream.writeBytes(postData); 
	        writeStream.flush();
	        writeStream.close();
				
	        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        String line="";
	        String result = "";
	        logger.info("<----------------response from Tencent Start---------------->");
	        while ((line = reader.readLine()) != null){
	        	result = result + line;
	        }
	        return result;
		} catch(Exception e) {
		    logger.error(e);
			return null;
		} finally {
		    connection.disconnect();
		}
		
    }
}
